import type { RouteRecordRaw } from "vue-router";
import { BuildRoutes } from "@/router/build";
import { joinParentPath } from "@/router/helper";
import { cloneDeep } from "lodash-es"
import { usePermissionStore } from "@/store/modules/permissionStore";
import { useUserStore } from '@/store/modules/userStore';


//构建动态路由
export function buildRoutesAction() {
    let perStore = usePermissionStore()
    let userStore = useUserStore()
    try {
        let asyncRouterDeep = cloneDeep(BuildRoutes.ASYNC_ROUTERS_LIST)
        //修改路由path
        joinParentPath(asyncRouterDeep)
        //挂载异步路由
        asyncRouterDeep.forEach(route => {
            let { meta } = route || {}

            if ((meta?.roles && meta.roles.includes(userStore.role)) || !meta?.roles) {
                BuildRoutes.ROUTER.addRoute(route as unknown as RouteRecordRaw)
            }
        })
        perStore.setIsDynamicAddedRoute(true)

    } catch {
        throw new Error('挂载异步路由失败')
    }

}

